//
//  ZFMainViewController.swift
//  WeiBoAPP
//
//  Created by 张学飞 on 2018/12/28.
//  Copyright © 2018 zxf. All rights reserved.
//

import UIKit


class ZFMainViewController: UITabBarController {

    private var timer:Timer?
    private var  count:Int = 0

    // MARK: - LiftCyle
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        setupChildControllers()
        setupComposeButton()
        searchPath()
        setupTimer()
        //加载新特性
//        setupNewfeatureViews()
        
        
        //设置代理
        delegate = self
        
        
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(userLoginNotification),
                                               name: NSNotification.Name?(NSNotification.Name(rawValue: WB_LoginRegist_NNotification)),
                                               object: nil)
    }
    
    deinit {
        //销毁定时器
        
        timer?.invalidate()
        NotificationCenter.default.removeObserver(self)
    }
    
    // MARK: 设备
    /**
     portrait:竖屏，
     landscape:横屏
     */
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask
    {
        return .portrait
    }
    
    
   // MARK: - 监听方法
    //撰写微博 private 私有的，当前对象可访问
    //@objc x允许这个函数在运行时通过OC的消息机制被调用
    @objc private func composeStatus()
    {
        print("撰写微博")

        let currentVC = Tool.currentController()
        currentVC.navigationController?.pushViewController(ZFDiscoverViewController.init(), animated: true)
    }
    
    
    // MARK: - 懒加载
    
    private lazy var composeButton:UIButton = {
        let composeButton = UIButton(type: UIButton.ButtonType.custom)
        composeButton.setImage(UIImage(named: "hotNavgation_undeselectd"), for: UIControl.State.normal)
        composeButton.setImage(UIImage(named: "hotNavgation_deselectd"), for: UIControl.State.selected)
        composeButton.addTarget(self, action:#selector(composeStatus), for: .touchUpInside)

        return composeButton
    }()

}

// MARK: - 通知
extension ZFMainViewController {
    
    @objc func userLoginNotification(notinfation:Notification)  {
        
        let vc = ZFOAuthViewController()
        let nav = UINavigationController.init(rootViewController: vc)
        present(nav, animated: true, completion: nil)
        
    }
    
}

// MARK: - 代理
extension ZFMainViewController :UITabBarControllerDelegate {
    
    //
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        print("将夜切换到 \(viewController)")
        //
        let idx = (childViewControllers as NSArray).index(of: viewController)
        //重复点击首页按钮
        if selectedIndex == 0 && idx == selectedIndex {
            print("点击首页")
            //表格滚动大顶部
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! ZFHomeViewController
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            
            
            //刷新数据 证件延迟
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {

                self.count = 0
                self.setTabbarBageCount(count: 0)
                //                print("延迟加载数据")r
            }
            
        }
        
         //判断是不是控制器
       return !viewController.isMember(of: UIViewController.self)
        
//        return true
    }

}


// MARK: - 定义时钟
extension ZFMainViewController {

    private func setupTimer () {
        timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(updataTimer), userInfo: nil, repeats: true)

    }
    //定时器
    @objc private func updataTimer () {
        count  = count + 1
            
        self.tabBar.items?[0].badgeValue = "\(count)"
        //ios 8.0 只之后需要用户授权 10.0以后的y有所不同
        UIApplication.shared.applicationIconBadgeNumber = count
//        print("定时器个数 \(count) 主线程： \(Thread.isMainThread ? "YES" : "NO" )")
//        WBNetworkManager.shared.unreadCount { (count) in
//            print("个数")
//        }
    }
    
}

// MARK: -  extension
/**
 extension 类似于OC中的分类，在swift中国还可以用来切分代码块
 把相近的功能函数放在z一个extension中，方便维护，不能定义属性
 */
extension ZFMainViewController {
    
  // MARK: - 设置界面
    private func setupComposeButton()
    {
        tabBar.addSubview(composeButton)
        let count = CGFloat(childViewControllers.count)
        //盖住容错点
        let w = tabBar.bounds.width/count - 1
        //正数向内缩，负数向外扩展
        composeButton.frame = tabBar.bounds.insetBy(dx: 2*w , dy: -10)
        
        
    }
    
    private func setupChildControllers()
    {
        
        let array = [
            ["clsName":"ZFHomeViewController","title":"首页","imageName":"1"],
            ["clsName":"ZFWeiBoViewController","title":"微博","imageName":"2"],
            ["clsName":"ZFDiscoverViewController","title":"","imageName":"none"],
            ["clsName":"ZFMessageViewController","title":"消息","imageName":"2"],
            ["clsName":"ZFMineViewController","title":"我的","imageName":"4"],

            ]
        var arrayM = [UIViewController]()
        for dic in array {
            arrayM.append(controller(dic: dic))
        }
        viewControllers = arrayM
        
        //数组序列化
//        let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentationDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        
        var url =  NSHomeDirectory() //path.first
        url.append("/Documents/testdata")
        print( url)
        let data  = try? JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
        (data! as NSData).write(toFile: url, atomically: true)
        
    }

    
    //创建子控制器 dic [clsName,title,imageName]
    private func controller(dic:[String: String]) ->UIViewController {
        
        guard let clsName = dic["clsName"],
            let  title = dic["title"],
            let imageName = dic["imageName"],
            let cls = NSClassFromString(Bundle.nameSpace(clsName: clsName)) as? UIViewController.Type
    
        else  {
            return ZFNavigationController.init(rootViewController:UIViewController())
        }
        
        let vc = cls.init()
        vc.title = title
        vc.tabBarItem.image = UIImage(named: "image-" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "image-" + imageName + "-h")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
        
        //标题字体,字体大小默认12
        vc.tabBarItem.setTitleTextAttributes([.foregroundColor: UIColor.orange],
                                             for: .selected)
        vc.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.font:UIFont.systemFont(ofSize: 16)],
                                             for:UIControl.State(rawValue: 0))
        //实例化导航，会执行push
        let nav = ZFNavigationController.init(rootViewController: vc)
        
        
        return nav
    }
    
    
    func searchPath ()  {
        print("***NSSearchPathForDirectoriesInDomains路径**************")
        let libraryPath:String = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.libraryDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]
        print("library路径----\(libraryPath)")
        
        let cachePath:String = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]
        print("Cache路径----\(cachePath)")
        
        let preferPath:String = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.preferencePanesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]
        print("Prefer路径----\(preferPath)")
        
        let homeDir:String = NSHomeDirectory()
        print("沙盒地址---\(homeDir)")
        
        let imagePath = Bundle.main.path(forResource: "sale", ofType: "png")
        print("FlyElephnt-图片路径----\(imagePath ?? "")")
        let bundlePath = Bundle.main.bundleURL.path
        print("FlyElephnt-App资源文件路径--\(bundlePath)")
        
        let testDataPath = Bundle.main.bundleURL.appendingPathComponent("FlyElephant").path
        print("压缩文件的路径---\(testDataPath)")
        
        print("***NSSearchPathForDirectoriesInDomains…*************")

    }
}


extension ZFMainViewController {
    
    func setTabbarBageCount(count: Int )  {
        if count == 0 {
            
            self.tabBar.items?[0].badgeValue = nil
            //ios 8.0 只之后需要用户授权 10.0以后的y有所不同
            UIApplication.shared.applicationIconBadgeNumber = 0

            return
        }
        self.tabBar.items?[0].badgeValue = "\(count)"
        //ios 8.0 只之后需要用户授权 10.0以后的y有所不同
        UIApplication.shared.applicationIconBadgeNumber = count

    }
    
}

// MARK: - 新特性
extension ZFMainViewController {
    
    /**
     extension 中可以有计算性属性，不会占用存储空间
     构造函数给属性分配空间
     版本号
     在App Store 每次升级应用程序，版本号都需要增加
     组成 主版本号 此版本号 修订版本号
     主版本号：意味着大的修改，使用者也需要做打的适应
     次版本号：意味着小的修改，某些函数和方法的使用或者参数有变化
     修订版本傲：框架/程序内部bug的修改，不会对使用者造成任何的影响
     
     
     */
    
   private func setupNewfeatureViews ()  {
    
    
    
    //1 检查版本是否更新
    let v = !isNewVersion ? ZFNewFeatureView() : ZFNewConView.welcomeView()
    v.frame = view.bounds
    view.addSubview(v)
    
    
    }
    
    
    private var isNewVersion:Bool {
        
        //取当前版本号，
        print(Bundle.main.infoDictionary ?? "")
        
        // 取保存在Documents中的之前的版本号
        let currentVersion = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? ""
        let path:String = ("version" as NSString).appending("")
        let sanboxVersion = (try? String(contentsOfFile: path))
        print(sanboxVersion)
        
        //将当前版本号保存到沙盒里
        _ = try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        
        
        return currentVersion != sanboxVersion

        
        // 和当前版本a号对比，
        
        
        return true
    }
}
